import { useState, useEffect } from 'react';

interface DashboardStats {
  piping: number;
  electrical: number;
  hvac: number;
  communication: number;
  instrumentation: number;
}

interface SpecialtyDetail {
  name: string;
  deviceCount: number;
  typeCount: number;
  enteredDevices: number;
  validatedDevices: number;
  entryRate: number;
  validationRate: number;
}

interface DashboardData {
  stats: DashboardStats;
  typeStats: DashboardStats;
  totalDevices: number;
  totalDeviceTypes: number;
  enteredDevices: number;
  validatedDevices: number;
  overallEntryRate: number;
  overallValidationRate: number;
  specialtyDetails: SpecialtyDetail[];
}

export function useDashboardStats() {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchStats() {
      try {
        if (!loading) setLoading(true);
        const response = await fetch('/api/dashboard-stats');
        if (!response.ok) {
          throw new Error('获取统计数据失败');
        }
        const responseData = await response.json();
        if (responseData.success) {
          setData({
            stats: responseData.stats,
            typeStats: responseData.typeStats,
            totalDevices: responseData.totalDevices,
            totalDeviceTypes: responseData.totalDeviceTypes,
            enteredDevices: responseData.enteredDevices,
            validatedDevices: responseData.validatedDevices,
            overallEntryRate: responseData.overallEntryRate,
            overallValidationRate: responseData.overallValidationRate,
            specialtyDetails: responseData.specialtyDetails
          });
        } else {
          throw new Error(responseData.error || '获取统计数据失败');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '未知错误');
      } finally {
        setLoading(false);
      }
    }

    fetchStats();
    
    const interval = setInterval(fetchStats, 5000); // Refresh every 5 seconds
    return () => clearInterval(interval);

  }, []);

  return {
    data,
    stats: data?.stats || null,
    totalDevices: data?.totalDevices || 0,
    loading,
    error
  };
}